<?php
/**
 * C微信(或易信)公共平台处理类
 */
include_once __DIR__ . '/Interface.php';
include_once __DIR__ .'/bs/bs.Weizhida.php';
include_once __DIR__ . '/hermes.BusinessObject.php';
/**
 * Class C微信
 */
class C微信 extends C接口
{
    public $isTest = false;
    public $serv_id =G_SERV_ID;
    protected $accessToken = null;
    //当前用户openid
    protected  $userOpenId ;
    //当前公众号openid
    protected $gzhOpenId ;
    protected $vo信息中心;
    private $appToken = ""; // TOKEN值 此外系统中还有一个 access token 要注意区分
   // private $articles = array();
    private $appId ;
    private $appSecret ;

    /**
     * 构造函数
     * @param string $userOpenId
     * @param string $gzhOpenId
     * @param string $appToken
     * @param string $appId
     * @param string $appSecret
     * @return C微信 新生成的WeChat类实例
     */
    //TODO 入口参数优化。信息中心已经包含了 前面两个参数
    function __construct($userOpenId,$gzhOpenId,C信息中心 $vo信息中心)
    {
        parent::__construct();
        if($gzhOpenId) $this->serv_id=wzd()->getServId($gzhOpenId);
        $this->vo信息中心=$vo信息中心;
        if(!empty($userOpenId)) $this->userOpenId=$userOpenId;
        if(!empty($gzhOpenId)) $this->gzhOpenId=$gzhOpenId;



        $this->appToken = $vo信息中心->vs公众号AppToken;
        $this->appId = $vo信息中心->vs公众号AppId;
        $this->appSecret =$vo信息中心->vs公众号AppSecret;
    }
    /**
     * @param null|string $gzhOpenId
     */
    public function setGzhOpenId($gzhOpenId)
    {
        $this->gzhOpenId = $gzhOpenId;
    }

    /**
     * @param null|string $userOpenId
     */
    public function setUserOpenId($userOpenId)
    {
        $this->userOpenId = $userOpenId;
    }

    /**
     * 检查签名是否正确
     * @param $signature
     * @param $timestamp
     * @param $nonce
     * @param string $appToken
     * @return boolean 正确返回true,否则返回false
     */
    public static function f验证签名($signature, $timestamp, $nonce,$公众号Id)
    {
        $token = 'errtoken找不到公众号id';
/*        if (!empty($appid)) {
        $do公众号 = new DoPublic_serv_accounts();
        $do公众号->set_id($appid);
        $do公众号->loadByKeys($do公众号->data);
        $token = $do公众号->get_token();
        }
*/
        global $G_CONFIG;
        $token = $G_CONFIG['公众号信息'][$公众号Id]['公众号Token'];

        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param $vt消息文本
     * @return DoMessage
     */


    public static function f解析消息文本($vt消息文本){
        $wxData = simplexml_load_string($vt消息文本, 'SimpleXMLElement', LIBXML_NOCDATA);
        $type = trim((string)$wxData->MsgType);

        //根据微信传回的xml文本,构建当前消息对象
        $v当前消息=new DoMessage();
        $v当前消息->set_message_type($type); // 取得消息类型
        $v当前消息->set_from_user_name( (string)$wxData->FromUserName);
        $v当前消息->set_to_user_name( (string)$wxData->ToUserName);
        $v当前消息->set_create_time( (string)$wxData->CreateTime);
        $v当前消息->set_id( (string)$wxData->MsgId);

        switch ($type) {
            case 'text':
                $v当前消息->set_content( (string)$wxData->Content);
                break;
            case 'image':
                $v当前消息->set_media_id( (string)$wxData->MediaId);
                $v当前消息->set_pic_url((string)$wxData->PicUrl);
                $v当前消息->set_content('图片');
                break;
            case 'voice':
                $v当前消息->set_media_id( (string)$wxData->MediaId);
                $v当前消息->set_format( (string)$wxData->Format);
                $v当前消息->set_content( (string)$wxData->Recognition); //语音识别结果
                break;
            case 'video':
                $v当前消息->set_media_id( (string)$wxData->MediaId);
                $v当前消息->set_thumb_media_id( (string)$wxData->ThumbMediaId);
                $v当前消息->set_content('视频');
                break;
            case 'location':
                $v当前消息->set_label( (string)$wxData->Label);
                $v当前消息->set_scale( (string)$wxData->Scale);
                $v当前消息->set_location_x( (string)$wxData->Location_X);
                $v当前消息->set_location_y( (string)$wxData->Location_Y);
                $v当前消息->set_content('位置');
                break;
            case 'link':
                $v当前消息->set_title( (string)$wxData->Title);
                $v当前消息->set_description((string)$wxData->Description);
                $v当前消息->set_url((string)$wxData->$Url);
                $v当前消息->set_content('链接');
                break;
            case 'event':
                $v当前消息->set_event((string)$wxData->Event);
                $v当前消息->set_event_key( (string)$wxData->EventKey);
                if($v当前消息->get_event()=='scancode_waitmsg'){
                    $v当前消息->set_scancodeinfo_scantype($wxData->ScanCodeInfo->ScanType);
                    $v当前消息->set_scancodeinfo_scanresult($wxData->ScanCodeInfo->ScanResult);
                }
                $v当前消息->set_content('事件');
                break;
            default:
                break;

        }
        $v当前消息->ticket = self::ff解析微信消息返回ticket($vt消息文本);
        return $v当前消息;
    }

    private static function ff解析微信消息返回ticket($str) {
        $xml = simplexml_load_string($str);
        return (string) $xml->Ticket;
    }

    /**
     * @param DoMessage $msg
     * @param string $toUser
     * @param string $fromUser
     * @return string
     */
    public function fh回复消息(DoMessage $msg, $toUser = '', $fromUser = '')
    {
        if (empty($toUser)) $toUser = $this->userOpenId;
        if (empty($fromUser)) $fromUser = $this->gzhOpenId;


        logger()->logDebug("-".__LINE__."-textResponse #toUser:" . $toUser . "-#fromUser:" . $fromUser . "-#msg:" . $msg->get_message_type().$msg->get_content());

        $type = $msg->get_message_type();

        $xmlTemplate = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    ";
        $xmlText = sprintf($xmlTemplate, $toUser, $fromUser, time());

        switch ($type) {
            case 'text':
                $xmlTemplate = "<MsgType><![CDATA[text]]></MsgType>
                                <Content><![CDATA[%s]]></Content>
                                 </xml>";
                $xmlText = $xmlText . sprintf($xmlTemplate, $msg->get_content());

                break;
            case 'image':
                $xmlTemplate = "<MsgType><![CDATA[image]]></MsgType>
                                <Image>
                                <MediaId><![CDATA[%s]]></MediaId>
                                </Image>
                                </xml>";
                $xmlText = $xmlText . sprintf($xmlTemplate, $msg->get_media_id());

                break;
            case 'voice':
                $xmlTemplate = "<MsgType><![CDATA[voice]]></MsgType>
                                <Voice>
                                <MediaId><![CDATA[%s]]></MediaId>
                                </Voice>
                                </xml>";
                $xmlText = $xmlText . sprintf($xmlTemplate, $msg->get_media_id());

                break;
            default:
                $xmlTemplate = "<MsgType><![CDATA[text]]></MsgType>
                                <Content><![CDATA[%s]]></Content>
                                 </xml>";
                $xmlText = $xmlText . sprintf($xmlTemplate, $msg->get_content());

                break;
        }
        //logger()->logDebug($xmlText);
        return $xmlText;

    }

    public function fh链接客服( $toUser = '', $fromUser = '' , $前台工号 = '')
    {
        if (empty($toUser)) $toUser = $this->userOpenId;
        if (empty($fromUser)) $fromUser = $this->gzhOpenId;

        $xmlTemplate = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    ";
        $xmlText = sprintf($xmlTemplate, $toUser, $fromUser, time());

        //  <TransInfo><KfAccount><![CDATA[003@weizhidalinhe]]></KfAccount></TransInfo>
        // <Content><![CDATA[%s]]></Content>
        if($前台工号){
            $xmlTemplate = "<MsgType><![CDATA[transfer_customer_service]]></MsgType>
           <TransInfo><KfAccount><![CDATA[".$前台工号."]]></KfAccount></TransInfo>
            </xml>";
        }else{
            $xmlTemplate = "<MsgType><![CDATA[transfer_customer_service]]></MsgType>
            </xml>";
        }



        $xmlText = $xmlText . $xmlTemplate;

        //logger()->logDebug($xmlText);

        logger()->logDebug($xmlText);

        return $xmlText;

    }

    /**
     * 形成 文本消息响应值
     *
     * @param string $content
     * @param string $toUser
     * @param string $fromUser
     * @param int $flag
     * @return string
     */
    public function fh生成文本消息($content, $toUser = NULL, $fromUser = NULL, $flag = 0)
    {
        if (empty($toUser)) $toUser = $this->userOpenId;
        if (empty($fromUser)) $fromUser = $this->gzhOpenId;

        logger()->logDebug("-".__LINE__."-textResponse #toUser:" . $toUser . "-#fromUser:" . $fromUser . "-#content:" . $content);

        $xmlTemplate = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>%d</FuncFlag>
                    </xml>";
        $xmlText = sprintf($xmlTemplate, $toUser, $fromUser, time(), $content, $flag);
        return $xmlText;
    }

    public function fh回复页面链接($pageName, $description)
    {
        $vo消息列表=new Cbo图文消息列表();
        $baseUrl = G_SITE_BASE.'/business/';

        return $this->fh生成图文消息($vo消息列表);
    }

    public static function GetTransmitUrl( $vs参数, $appId ,$公众号Id,$url=G_WX_ROUTE_PAGE)
    {

        return self::$tools->GetTransmitUrl($vs参数,$appId,$公众号Id);
        /*
        $url1 = urlencode($url);
        if (is_array($vs参数)) //如果是传多个参数
            $state = "000" . urlencode(json_encode($vs参数));
        else
            $state = $vs参数;
        return $wxUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appId}&redirect_uri={$url1}&response_type=code&scope=snsapi_base&state={$state}#wechat_redirect";
    */
    }


    /**
     * 形成 图文消息响应值
     *
     * @param Cbo图文消息列表 $articles
     * @param string $toUser
     * @param string $fromUser
     * @return string
     */
    public function fh生成图文消息 (Cbo图文消息列表 $articles,$toUser = null, $fromUser = null)
    {
        if($articles->vi消息数量<1) return 'zero article.';
        if (empty($toUser)) $toUser = $this->userOpenId;
        if (empty($fromUser)) $fromUser = $this->gzhOpenId;

        $xmlTemplate = "<xml>
    			    <ToUserName><![CDATA[%s]]></ToUserName>
    			    <FromUserName><![CDATA[%s]]></FromUserName>
    			    <CreateTime>%s</CreateTime>
    			    <MsgType><![CDATA[news]]></MsgType>
    			    ";
        $xmlText = sprintf($xmlTemplate, $toUser, $fromUser, time());
        $xmlText .= '<ArticleCount>' . $articles->vi消息数量 . '</ArticleCount>';
        $xmlText .= '<Articles>';
        foreach ($articles->va消息列表 as $article) {
            $xmlText .= '<item>';
            $xmlText .= '<Title><![CDATA[' . $article['标题'] . ']]></Title>';
            $xmlText .= '<Description><![CDATA[' . $article['描述'] . ']]></Description>';
            $xmlText .= '<PicUrl><![CDATA[' . $article['图片链接'] . ']]></PicUrl>';
            $xmlText .= '<Url><![CDATA[' . $article['页面链接'] . ']]></Url>';
            $xmlText .= '</item>';
        }
        $xmlText .= '</Articles> </xml>';
        return $xmlText;
    }

    public function ResponseBlank()
    {
        logger()->logDebug("---sendBlack called---");
        return "";
    }

    public function ff发送文本消息($messageTxt, $toUserID = null)
    {
        $msg = new DoMessage();
        $msg->set_content($messageTxt);
        $msg->set_message_type('text') ;
        $msg->set_to_user_name(empty($toUserID)?$this->userOpenId:$toUserID);


        return $this->ff发送消息($msg);
    }

    /**
     * 发送非即时响应消息
     * @param DoMessage $message
     * @param null $vs用户openId
     * @return mixed <boolean, mixed>
     */
    public function ff发送消息(DoMessage $message,$vs用户openId=null)
    {

        if(empty($vs用户openId))
            $toUserID = $message->get_to_user_name();
        else{
            $toUserID=$vs用户openId;
            $message->set_to_user_name($toUserID);
        }

        if (empty($toUserID ))
            $toUserID = $this->userOpenId;

        $messageType=$message->get_message_type();
        $content=$message->get_content();
        $info = '[' . $messageType . ']' .$content ;

        logger()->logInfo("---send Client MSG [msg]:" . $info . "[User]:" . $toUserID);

        if (empty($this->accessToken)) $this->accessToken = $this->vo信息中心->vc微直达->getAccessToken();
//        $用户所在公众号 = self::$pdo->selectColumns('用户',array('公众号ID'),array('openID'=>$toUserID));
//        $token = self::$pdo->selectColumns('UniversalParameters',array('value'),array('公众号ID'=>$用户所在公众号['公众号ID']));
//        $this->accessToken = $token['value'];
        //if()

        switch ($messageType) {
            case 'text':
                $cont = '{
                "touser": "' . $toUserID . '",
                "msgtype": "text",
                "text": {
                    "content": "' . $content . '"
                }
                }';

                break;
            case 'image':
                $cont = '{
                "touser": "' . $toUserID . '",
                "msgtype": "image",
                "image": {
                    "media_id": "' . $message->get_media_id() . '"
                }
                }';

                break;
            case 'voice':
                $cont = '{
                "touser": "' . $toUserID . '",
                "msgtype": "voice",
                "voice": {
                    "media_id": "' . $message->get_media_id() . '"
                }
                }';

                break;
            case 'news':
                $cont = '{
                        "touser":"' . $toUserID . '",
                        "msgtype":"news",
                        "news":{' . $message->get_news() . '}
                    }';
                break;
            default:
                $cont = '{
                "touser": "' . $toUserID . '",
                "msgtype": "text",
                "text": {
                    "content": "' . $content . '"
                }
                }';
        }

        $url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$this->accessToken";

        $ret = $this->curl_post_page($url,$cont);
//        if($messageType=='text' || $messageType=='news') {
//            $this->记录图文和文本发送消息($message,$ret);
//        }
        logger()->logDebug("---sendClientMSG result---with #ret:" . $ret);

        return $ret;
    }
   public function 记录图文和文本发送消息(DoMessage $message,$消息发送结果) {
        $接收消息用户openID = $message->get_to_user_name();
        $公众号信息 = pdo()->selectColumns('用户',array('公众号ID','公众号openID'),array('openID'=>$接收消息用户openID));
        if($message->get_message_type()=='news') {
            $type = '图文消息';
            $content = self::返回用户发送图文消息内容($message);
        }else {
            $type = '文本消息';
            $str = $message->get_content();
            $str = str_replace(array("\r\n","\r","\n"),'',$str);
            $content = '{
                "text": {
                    "content": "' . $str . '"
                }
                }';

            $content = json_decode($content);
            $文本内容 = mb_substr($content->text->content,0,20,'utf8');
//            $content = urlencode($文本内容);
            $content = $文本内容;
        }

        $发送结果 =  json_decode($消息发送结果);
        if($发送结果->errcode) {
            $结果  = '否';
        }else {
            $结果  = '是';
        }

        $do = new Do消息发送记录();
        $do -> set_接收消息用户openID($接收消息用户openID);
        $do -> set_消息类型($type);
        $do -> set_发送时间(Date('Y-m-d H:i:s'));
        $do -> set_是否正确发送($结果);
        $do -> set_错误代码($发送结果->errcode);
        $do -> set_消息内容($content);
        $do -> set_公众号ID($公众号信息['公众号ID']);
        $do -> set_公众号openID($公众号信息['公众号openID']);
        $do -> save();
    }

    public function ff发送图文消息( Cbo图文消息列表 $articles,$toUserID = null)
    {

        $msg = new DoMessage();
        $msg->set_message_type('news');

        $msg->set_to_user_name(empty($toUserID)?$this->userOpenId:$toUserID);
        $n ='"articles": [';
        $i = 0;
        foreach ($articles->va消息列表 as $art) {
            $i++;
            if ($i > 1) $n .= ',';
            $n .= '{';
            $n .= '"title":"' . $art['标题'] . '",';
            $n .= '"description":"' . $art['描述'] . '",';
            $n .= '"picurl":"' . $art['图片链接'] . '",';
            $n .= '"url":"' . $art['页面链接'] . '"';
            $n .= '}';

        }
        $n .= ']';
        $msg->set_news($n);

        return $this->ff发送消息($msg);
    }

    /**
     * @param string $menu
     * @param $accessToken
     * @return mixed
     */
    public static function CreateMenu($menu,$accessToken=null)
    {

        logger()->logInfo("---CreateMenu called [menu]:" . $menu);
        if (empty($accessToken)) $accessToken=wzd()->vc微直达->getAccessToken();
        $url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=$accessToken";

        $cont = $menu;
        $ret = self::$tools->curl_post_page($url,$cont);

        logger()->logInfo("---CreateMenu result---with #ret:" . $ret);

        return $ret;
    }

    public static function GetMenu($accessToken=null)
    {

        logger()->logInfo("---GetMenu called [token]:" . $accessToken);
        if (empty($accessToken)) $accessToken=wzd()->vc微直达->getAccessToken();
        $url="https://api.weixin.qq.com/cgi-bin/menu/get?access_token=$accessToken";

        $ret = self::$tools->curl_get_contents($url);

        logger()->logInfo("---GetMenu result---with #ret:" . $ret);

        return $ret;
    }
    /**
     * @param $accessToken
     * @return mixed
     */
    public static function DeleteMenu($accessToken=null)
    {
        if (empty($accessToken)) $accessToken=wzd()->vc微直达->getAccessToken();
        logger()->logInfo("---DeleteMenu called ---");
        $url="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=$accessToken";
        $ret =self::$tools->curl_get_contents($url);
        logger()->logInfo("---DeleteMenu result---with #ret:" . $ret);
       return $ret;
    }

    /**
     * 从微信获取当前AccessToken
     *
     * @param string $appId
     * @param string $secret
     * @return string  <boolean, mixed, multitype:>

    public function getAccessTokenNew($appId=G_APP_ID, $secret=G_APP_SECRET)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/token';
        $params = array(
            'grant_type' => 'client_credential',
            'appid' => $appId,
            'secret' => $secret
        );

        $ret = $this->curl_post_page($url, $params);

        if (!$ret) {
            logger()->logError(var_export($ret,true));
            return false;
        }

        $decd = json_decode($ret);
        return $decd->access_token;
    }  */
    public function getAccessTokenNew()
    {
        $appId = $this->vo信息中心->vs公众号AppId;
        $secret = $this->vo信息中心->vs公众号AppSecret;
        $url = 'https://api.weixin.qq.com/cgi-bin/token?';
        $params = array(
            'grant_type' => 'client_credential',
            'appid' => $appId,
            'secret' => $secret
        );

//        $ret = $this->curl_post_page($url, $params);
        $ret = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$secret);

        if (!$ret) {
            logger()->logError(var_export($ret,true));
            return false;
        }

        $decd = json_decode($ret);
        return $decd->access_token;
    }

    /**
     * 微信中打开第三方页面，利用微信Oauth接口获得用户OpenId
     * @param $_appId
     * @param $_secret
     * @return mixed|null
     */
    public function GetOuterPageOauth($_appId, $_secret)
    {
        if ($_appId)
            $appId = $_appId;
        else
            $appId = $this->appId;
        if ($_secret)
            $secret = $_secret;
        else
            $secret = $this->appSecret;

        $code = $_REQUEST['code'];
        //$state = $_REQUEST['state'];
        if ($code) {
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appId}&secret={$secret}&code={$code}&grant_type=authorization_code";
            //return $url."<br>";
            $ret = $this->curl_get_contents($url);
            $obj = json_decode($ret);
            return $obj->openid;
            //return $ret;
        } else {
            return null;
        }
        /* 返回数据格式：
         * {
               "access_token":"ACCESS_TOKEN",
               "expires_in":7200,
               "refresh_token":"REFRESH_TOKEN",
               "openid":"OPENID",
               "scope":"SCOPE"
            }
         */
    }

    function curl_get_contents($url, $timeout = 3)
    {
        //初始化

        $ch = curl_init();

        //设置选项，包括url

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($ch,CURLOPT_AUTOREFERER,1);
        curl_setopt($ch, CURLOPT_HEADER, 0);

        //执行并获取html内容

        $output = curl_exec($ch);

        //释放curl句柄

        curl_close($ch);

        return $output ;
    }

    /**
     * @param $fileName
     * @param string $type
     * @param null $token
     * @return bool
     */
    function UploadMedia($fileName,$type='image',$token=null)
    {
        //$type = "image";
        if(empty($token))  $token=$this->accessToken;
        if(empty($token)) $token=$this->vo信息中心->vc微直达->getAccessToken();


        $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={$token}&type={$type}";
        $result = $this->curl_post_file($url, $fileName);
        $obj=json_decode($result);

        logger()->logDebug2($obj,"上传多媒体文件");

        if($obj->media_id){
             return $obj->media_id;
        }else{
            return false;
        }
    }

    /**
     * @return bool|string
     */
    public function f获取用户基本信息(){
        if(empty($this->accessToken)) $this->accessToken=wzd()->vc微直达->getAccessToken();
        $openId=$this->userOpenId;
        $url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->accessToken."&openid=$openId&lang=zh_CN";
        $result=$this->curl_get_contents($url);
        logger()->logDebug2($result,'用户信息:');
        if($result)
            return $result;
        else
            return false;
        /*
         {
            "subscribe": 1,
            "openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M",
            "nickname": "Band",
            "sex": 1,
            "language": "zh_CN",
            "city": "广州",
            "province": "广东",
            "country": "中国",
            "headimgurl":    "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
           "subscribe_time": 1382694957,
           "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
         }
         */
    }
    //todo 多收银台22
    function curl_post_page($url, $data, $timeout = 4)
    {
//        var_dump($url,$data);
//        $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": a1123}}}';
//        $data = 123;
//        var_dump($data);
////        $url = "http://localhost/aaa.php";
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
//        // post数据
//        curl_setopt($ch, CURLOPT_POST, 1);
//        // post的变量
//        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//
//        $output = curl_exec($ch);
//        var_dump($output);die;
//        curl_close($ch);

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"POST");
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($ch,CURLOPT_AUTOREFERER,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        $output = curl_exec($ch);
        if(curl_errno($ch)){
            echo curl_error($ch);
        }
        return $output;
    }
    /*
    function curl_post_page($url, $data, $timeout = 4)
    {
        //$url = "http://localhost/web_services.php";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
*/
    function curl_post_file($url, $fileName, $timeout = 4)
    {
        //$cfile = curl_file_create($fileName); //php 5.5
        $cfile="@".$fileName; //php 5.3
        $filedata = array("media" => $cfile);

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_POST,1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $filedata);
        curl_setopt($ch, CURLOPT_INFILESIZE,filesize($fileName)); //这句非常重要，告诉远程服务器，文件大小，查到的是前辈的文章http://blog.csdn.net/cyuyan112233/article/details/21015351

        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    /**
     * @param $viCodeID
     * @param $vsFileName
     * @param bool $permanent
     * @return string[]|bool
     */
    function fc创建二维码($viCodeID, $vsFileName, $permanent = false,$时间 =1800)
    {
        if (empty($this->accessToken)) $this->accessToken = $this->vo信息中心->vc微直达->getAccessToken();
        $token = $this->accessToken;
        $returns = array();

        if ($permanent) {
            $type = 'QR_LIMIT_SCENE';
            $fname = Constants::e二维码_存放目录  . $vsFileName . '.jpg';
            $expire='"expire_seconds": '.$时间.',';
        } else {
            $type = 'QR_SCENE';
            $fname = Constants::e二维码_存放目录 . $vsFileName . '.jpg';
            $expire='"expire_seconds":  '.$时间.',';
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $token;
        $data = '{'.$expire.' "action_name": "' . $type . '", "action_info": {"scene": {"scene_id": ' . $viCodeID . '}}}';
        //根据id换取二维码图片

        $ret1 = $this->curl_post_page($url, $data);
        if ($ret1) {
            $dt = json_decode($ret1);
            $returns['message'] = $dt;
            $ticket = $dt->ticket;

            $ret2 = $this->curl_get_wximge($ticket);
           // $returns['img'] = $ret2.'.jpg';
             $returns['img'] = $fname.'.jpg';
            $returns['file_name'] = $fname;


            $fh = fopen($fname, 'w');

            if ($fh) {
                 fwrite($fh, $ret2);
                fclose($fh);
                return $returns;
            } else {
                return false;
            }

        } else {
            return false;
        }
    }

    //todo 多收银台11
    //todo 多收银台
    function fc创建字符二维码($viCodeID, $vsFileName, $permanent = true)
    {
        if (empty($this->accessToken)) $this->accessToken = $this->vo信息中心->vc微直达->getAccessToken();

        $token = $this->accessToken;

       // $token = self::getAccessTokenNew();

        $returns = array();

        if ($permanent) {
            $type = 'QR_LIMIT_STR_SCENE';
            $fname = Constants::e二维码_存放目录  . $vsFileName . '.jpg';
            $expire='';
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $token;
        $data = '{'.$expire.' "action_name": "' . $type . '", "action_info": {"scene": {"scene_str": "' . $viCodeID . '"}}}';

        $ret1 = $this->curl_post_page($url, $data);

        if ($ret1) {
            $dt = json_decode($ret1);
            $returns['message'] = $dt;
            $ticket = $dt->ticket;
            //根据id换取二维码图片

            $ret2 = $this->curl_get_wximge($ticket);
            $returns['img'] = $ret2.'.jpg';
            $returns['file_name'] = $fname;
            $fh = fopen($fname, 'w');
            if ($fh) {

                fwrite($fh, $ret2);
                fclose($fh);
                return $returns;
            } else {
                return false;
            }

        } else {
            return false;
        }
    }

    function curl_get_wximge($ticket)
    {
        $url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . urlencode($ticket);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $pkg = curl_exec($ch);
        curl_close($ch);
        return $pkg;
    }

    /**
     * 形成 音乐消息响应值
     *
     * @param string $toUser
     * @param string $fromUser
     * @param string $title
     * @param string $description
     * @param string $url
     * @param string $hq_url
     * @return string
     */
    private function ResponseMusic($toUser, $fromUser, $title, $description, $url, $hq_url = "")
    {
        $xmlTemplate = "<xml>
                     <ToUserName><![CDATA[%s]]></ToUserName>
                     <FromUserName><![CDATA[%s]]></FromUserName>
                     <CreateTime>%s</CreateTime>
                     <MsgType><![CDATA[music]]></MsgType>
                     <Music> <Title><![CDATA[%s]]></Title>
                     <Description><![CDATA[%s]]></Description>
                     <MusicUrl><![CDATA[%s]]></MusicUrl>
                     <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
                     </Music>
                     </xml>";
        if (empty($hq_url))
            $hq_url = $url;
        $xmlText = sprintf($xmlTemplate, $toUser, $fromUser, time(), $title, $description, $url, $hq_url);
        return $xmlText;
    }

    /**
     * 形成 图片消息的响应值
     *
     * @param string $toUser
     * @param string $fromUser
     * @param $mediaId
     * @internal param string $url
     * @return string
     */
    private function f回复图片($toUser, $fromUser, $mediaId)
    {
        $xmlTemplate = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[image]]></MsgType>
                        <Image>
                        <MediaId><![CDATA[%s]]></MediaId>
                        </Image>
                        </xml>";
        $xmlText = sprintf($xmlTemplate, $toUser, $fromUser, time(), $mediaId);
        return $xmlText;
    }

    /**
     * 形成 音频消息响应值
     *
     * @param $mediaId
     * @param string $fromUser
     * @param string $toUser
     * @internal param string $url
     * @internal param string $name
     * @internal param string $mimeType
     * @return string
     */
    private function ResponseVoice($mediaId, $fromUser, $toUser)
    {
        $xmlTemplate = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[voice]]></MsgType>
                        <Voice>
                        <MediaId><![CDATA[%s]]></MediaId>
                        </Voice>
                        </xml>";
        $xmlText = sprintf($xmlTemplate, $toUser, $fromUser, time(), $mediaId);
        logger()->logInfo("-".__LINE__."-textResponse #toUser:" . $toUser . "-#fromUser:" . $fromUser . "-#mediaId:" . $mediaId);
        logger()->logDebug($xmlText);
        return $xmlText;
    }

    /**
     * 形成 视频消息响应值
     *
     * @param string $toUser
     * @param string $fromUser
     * @param string $url
     * @param string $name
     * @param string $mimeType
     * @return string
     */
    private function ResponseVideo($toUser, $fromUser, $url, $name, $mimeType = 'video/mp4')
    {
        $xmlTemplate = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[video]]></MsgType>
                    <url><![CDATA[%s]]></url>
    			    <name><![CDATA[%s]]></name>
    			    <mimeType><![CDATA[%s]]></mimeType>
                    </xml>";
        $xmlText = sprintf($xmlTemplate, $toUser, $fromUser, time(), $url, $name, $mimeType);
        return $xmlText;
    }
}
